package org.afun.csms_android.tools;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

import org.afun.csms_android.R;

public class Music extends Service {
    private MediaPlayer mediaPlayer;

    @Override
    public void onCreate() {
        super.onCreate();

        mediaPlayer = MediaPlayer.create(this, R.raw.cyx);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopSelf();
            }
        });

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int action = intent.getIntExtra("action", 1);
        if (action == 1) {
            mediaPlayer.start();
            Toast.makeText(this, "开始播放", Toast.LENGTH_SHORT).show();
        } else if (action == 2) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            } else {
                Toast.makeText(this, "错误", Toast.LENGTH_SHORT).show();
            }

        }
        Intent in = new Intent("com.user.action");
        in.putExtra("action", action);
        sendBroadcast(in);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mediaPlayer.stop();
        Toast.makeText(this, "停止播放", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
